﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CronusModel;

namespace Cronus.ViewModel.Data
{
    public class Task
    {
        //*** Constants ***//
        //*** Static ***//
        //*** Member Variables ***//
        private CronusData.TasksRow _TaskRow;

        //*** Properties ***//
        public string TaskName
        {
            get { return _TaskRow.Name; }
            set { _TaskRow.Name = value; }
        }

        public IEnumerable<Activity> Activities
        {
            get { return null; }
        }

        public Project Project
        {
            get { return GetProject(); }
            internal set { SetProject(value); }
        }

        internal CronusData DataSet
        {
            get { return (CronusData)_TaskRow.Table.DataSet; }
        }

        internal CronusData.TasksRow TasksRow
        {
            get { return _TaskRow; }
        }

        //*** Events ***//
        //*** Constructors ***//
        internal Task(CronusData.TasksRow aTaskRow)
        {
            _TaskRow = aTaskRow;
        }

        IEnumerable<Activity> GetActivities()
        {
            return from activity in DataSet.Activities
                   where activity.TasksRow == TasksRow
                   select new Activity(activity);
        }

        public static Task CreateTask(DataModel dataModel, string taskName)
        {
            return CreateTaskRow(dataModel.TasksTable, null, taskName);
        }

        public static Task CreateTask(Project project, string taskName)
        {
            return CreateTaskRow(project.DataSet.Tasks, project, taskName);
        }

        static Task CreateTaskRow(CronusData.TasksDataTable tasks, Project project, string taskName)
        {
            var taskRow = tasks.NewTasksRow();
            taskRow.ProjectsRow = project.ProjectRow;
            taskRow.Name = taskName;
            tasks.AddTasksRow(taskRow);

            return new Task(taskRow);
        }

        //*** Abstract Methods ***//
        //*** Methods ***//

        /// <summary>
        /// Deletes this Task and all Activities associated with this task.
        /// </summary>
        internal void Delete()
        {
            // Remove any references to other activities before we end ourselves.
            while (Activities.Any())
                Activities.FirstOrDefault().ActivityRow.Delete();

            TasksRow.Delete();
        }

        private Project GetProject()
        {
            return new Project(_TaskRow.ProjectsRow);
        }

        private void SetProject(Project project)
        {
            if (null != project)
                _TaskRow.ProjectsRow = project.ProjectRow;
            else
                _TaskRow.ProjectsRow = null;
        }
    }
}
